package com.TeacherInfoServer.common.service.Impl;

import com.TeacherInfoServer.common.Result;
import com.TeacherInfoServer.exception.DepartmentNameNotExistException;
import com.TeacherInfoServer.exception.JobNumberRepeatedException;
import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.exception.TypeInfoNotExistException;
import com.TeacherInfoServer.listener.ExcelRespProp;
import com.TeacherInfoServer.mapper.TeacherMapper;
import com.TeacherInfoServer.pojo.DTO.AddTypeInfoDTO;
import com.TeacherInfoServer.pojo.DTO.SearchDTO.TeacherSearchDTO;
import com.TeacherInfoServer.pojo.DTO.TeacherDTO;
import com.TeacherInfoServer.pojo.entity.Department;
import com.TeacherInfoServer.pojo.entity.PositionHistory;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.vo.LearningExperienceListVo;
import com.TeacherInfoServer.pojo.vo.TeacherListVo;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 教师信息服务实现类
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    public TeacherMapper teacherMapper;
    @Autowired
    public TypeInfoService typeInfoService;
    @Autowired
    public CommentService commentService;

    @Override
    public Map<String, Object> getTeacherList( Integer pages, Integer size){
        Page<Teacher> page =new Page<>(pages,size);
        QueryWrapper<Teacher> queryWrapper =new QueryWrapper<>();
        //queryWrapper.orderBy(true, true, "LEFT(teacher_name, 1)");
        teacherMapper.getTeacherDTOListByPage(page,queryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("totals",page.getTotal());
        data.put("currentPages",page.getCurrent());
        data.put("pageNumber",page.getPages());
        data.put("rows",page.getRecords());
        return data;
    }

    @Override
    public Map<String,Object> searchTeacherList(TeacherSearchDTO teacherSearchDTO) {
        Page<LearningExperienceListVo> page = new Page<>(teacherSearchDTO.getPages(), teacherSearchDTO.getSize());
        teacherMapper.searchTeacherList(page, teacherSearchDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("totals", page.getTotal());
        data.put("currentPages", page.getCurrent());
        data.put("pageNumber", page.getPages());
        data.put("rows", page.getRecords());
        return data;
    }
    @Transactional
    @Override
    public void addTeacher(TeacherDTO teacherDTO){
        QueryWrapper<Teacher> queryWrapper =new QueryWrapper<>();
        if(typeInfoService.getOneId("民族类型",teacherDTO.getEthnic())==null){
            AddTypeInfoDTO addTypeInfoDTO = new AddTypeInfoDTO();
            addTypeInfoDTO.setCategory("teacherDict");
            addTypeInfoDTO.setName("民族类型");
            addTypeInfoDTO.setValue(teacherDTO.getEthnic());
            typeInfoService.addOne(addTypeInfoDTO);
        }
        if(typeInfoService.getOneId("学院类型",teacherDTO.getCollege())==null) {
            AddTypeInfoDTO addTypeInfoDTO = new AddTypeInfoDTO();
            addTypeInfoDTO.setCategory("teacherDict");
            addTypeInfoDTO.setName("学院类型");
            addTypeInfoDTO.setValue(teacherDTO.getCollege());
            typeInfoService.addOne(addTypeInfoDTO);
        }
        if(teacherMapper.selectOne(queryWrapper.eq("teacher_id",teacherDTO.getTeacherId()))==null) {
            Teacher teacher = new Teacher();
            Department department = commentService.findDepartmentByName(teacherDTO.getDepartment());
            teacher.setTeacherId(teacherDTO.getTeacherId());
            teacher.setTeacherName(teacherDTO.getTeacherName());
            teacher.setGender(teacherDTO.getGender());
            teacher.setBirthDate(teacherDTO.getBirthDate());
            teacher.setAge(teacherDTO.getAge());
            teacher.setIdCardNumber(teacherDTO.getIdCardNumber());
            teacher.setDepartmentId(department.getId());

            teacher.setJobTitleId(typeInfoService.getOneId("职称类型", teacherDTO.getJobTitle()));
            teacher.setDegreeId(typeInfoService.getOneId("学位类型", teacherDTO.getDegree()));
            teacher.setEducatedId(typeInfoService.getOneId("学历类型", teacherDTO.getEducated()));
            teacher.setEthnicId(typeInfoService.getOneId("民族类型", teacherDTO.getEthnic()));
            teacher.setCollegeId(typeInfoService.getOneId("学院类型",teacherDTO.getCollege()));
            teacherMapper.insert(teacher);
        }else {
            throw new JobNumberRepeatedException();
        }
    }

    @Transactional
    @Override
    public void updateTeacher(TeacherDTO teacherDTO){
        if(typeInfoService.getOneId("职称类型",teacherDTO.getJobTitle())==null){
            throw new TypeInfoNotExistException("职称类型不存在");
        }
        if(typeInfoService.getOneId("学位类型",teacherDTO.getDegree())==null){
            throw new TypeInfoNotExistException("学位类型不存在");
        }
        if(typeInfoService.getOneId("学历类型",teacherDTO.getEducated())==null){
            throw new TypeInfoNotExistException("学历类型不存在");
        }
        if(typeInfoService.getOneId("民族类型",teacherDTO.getEthnic())==null){
            throw new TypeInfoNotExistException("民族类型不存在");
        }
        Department department = commentService.findDepartmentByName(teacherDTO.getDepartment());
        if(department==null){
            throw new DepartmentNameNotExistException();
        }
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        if(teacherMapper.selectOne(queryWrapper.eq("id",teacherDTO.getId())
                .eq("teacher_id",teacherDTO.getTeacherId())
                .eq("teacher_name",teacherDTO.getTeacherName())
                .eq("gender",teacherDTO.getGender())
                .eq("birth_date",teacherDTO.getBirthDate())
                .eq("id_card_number",teacherDTO.getIdCardNumber())
                .eq("job_title_id",typeInfoService.getOneId("职称类型",teacherDTO.getJobTitle()))
                .eq("department_id",department.getId())
                .eq("degree_id",typeInfoService.getOneId("学位类型",teacherDTO.getDegree()))
                .eq("educated_id",typeInfoService.getOneId("学历类型",teacherDTO.getEducated()))
                .eq("ethnic_id",typeInfoService.getOneId("民族类型",teacherDTO.getEthnic()))
                .eq("college_id",typeInfoService.getOneId("学院类型",teacherDTO.getCollege())))!=null ) {

            throw new RecordExistDetailException("未进行修改");
        }
        QueryWrapper<PositionHistory> queryWrapper1 = new QueryWrapper<>();
        if(teacherMapper.selectOne(queryWrapper
                .eq("teacher_id",teacherDTO.getTeacherId())
                .eq("teacher_name",teacherDTO.getTeacherName())
                .eq("gender",teacherDTO.getGender())
                .eq("birth_date",teacherDTO.getBirthDate())
                .eq("id_card_number",teacherDTO.getIdCardNumber())
                .eq("job_title_id",typeInfoService.getOneId("职称类型",teacherDTO.getJobTitle()))
                .eq("department_id",department.getId())
                .eq("degree_id",typeInfoService.getOneId("学位类型",teacherDTO.getDegree()))
                .eq("educated_id",typeInfoService.getOneId("学历类型",teacherDTO.getEducated()))
                .eq("ethnic_id",typeInfoService.getOneId("民族类型",teacherDTO.getEthnic()))
                .eq("college_id",typeInfoService.getOneId("学院类型",teacherDTO.getCollege())))!=null ) {

            throw new RecordExistDetailException("未进行修改");
        }
        UpdateWrapper<Teacher> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("teacher_id", teacherDTO.getTeacherId())
                .set("teacher_id", teacherDTO.getTeacherId())
                .set("teacher_name", teacherDTO.getTeacherName())
                .set("gender", teacherDTO.getGender())
                .set("birth_date", teacherDTO.getBirthDate())
                .set("age", teacherDTO.getAge())
                .set("id_card_number", teacherDTO.getIdCardNumber())
                .set("job_title_id",typeInfoService.getOneId("职称类型",teacherDTO.getJobTitle()))
                .set("department_id",department.getId())
                .set("degree_id",typeInfoService.getOneId("学位类型",teacherDTO.getDegree()))
                .set("educated_id",typeInfoService.getOneId("学历类型",teacherDTO.getEducated()))
                .set("ethnic_id",typeInfoService.getOneId("民族类型",teacherDTO.getEthnic()))
                .set("college_id",typeInfoService.getOneId("学院类型",teacherDTO.getCollege()));
        teacherMapper.update(null,updateWrapper);
    }

    @Transactional
    @Override
    public Result<TeacherDTO> getOne(String teacher_id) {
        TeacherDTO teacherDTO=new TeacherDTO();
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        Teacher teacher = teacherMapper.selectOne(wrapper.eq(Teacher::getTeacherId, teacher_id));
        if(teacher==null){
            return Result.fail(null);
        }else {
            teacherDTO.setId(teacher.getId());
            teacherDTO.setTeacherId(teacher.getTeacherId());
            teacherDTO.setTeacherName(teacher.getTeacherName());
            teacherDTO.setGender(teacher.getGender());
            teacherDTO.setBirthDate(teacher.getBirthDate());
            teacherDTO.setIdCardNumber(teacher.getIdCardNumber());
            teacherDTO.setJobTitle(typeInfoService.getValue(teacher.getJobTitleId()));
            Department department = commentService.getById(teacher.getDepartmentId());
            teacherDTO.setDepartment(department.getName());
            teacherDTO.setDegree(typeInfoService.getValue(teacher.getDegreeId()));
            teacherDTO.setEducated(typeInfoService.getValue(teacher.getEducatedId()));
            teacherDTO.setEthnic(typeInfoService.getValue(teacher.getEthnicId()));
            teacherDTO.setAge(teacher.getAge());
            teacherDTO.setCollege(typeInfoService.getValue(teacher.getCollegeId()));
            return Result.success(200, "获取成功", teacherDTO);
        }
    }

    @Override
    public boolean deleteTeacher(List<String> teacherIds){
        QueryWrapper<Teacher> queryWrapper= new QueryWrapper<>();
        queryWrapper.in("teacher_id",teacherIds);
        int deleteCount=teacherMapper.delete(queryWrapper);
        return deleteCount>0;
    }

    @Override
    public Teacher findTeacherByName(String name){
        if (name == null || name.trim().isEmpty()) {
            // 参数为空或只包含空白字符，直接返回null
            return null;
        }

        try {
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teacher_name", name.trim()); // 保证查询条件不包含额外空格
            Teacher teacher = teacherMapper.selectOne(queryWrapper);
            return teacher; // 直接返回查询结果，避免了重复查询
        } catch (Exception e) {
            // 异常处理，例如记录日志等
            // log.error("查询教师异常", e);
            return null;
        }
    }

    @Override
    public Map<String, Object> getTeacherNameList(Integer pageNum, Integer pageSize, String teacherName) {
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Teacher::getTeacherId,Teacher::getTeacherName);

        if (teacherName != null && !teacherName.isEmpty()) {
            queryWrapper.like(Teacher::getTeacherName, teacherName);
        }

        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        Page<Map<String, Object>> result = teacherMapper.selectMapsPage(page, queryWrapper);

        return Map.of(
                "rows", result.getRecords().stream().map(teacher -> Map.of(
                        "teacherId", teacher.get("teacher_id"),
                        "teacherName", teacher.get("teacher_name")
                )).collect(Collectors.toList()),
                "total", result.getTotal()
        );
    }
    @Override
    @SneakyThrows(IOException.class)
    public void exportInfo(HttpServletResponse response){
        ExcelRespProp.setExcelRespProp(response, "教师信息列表");
        List<TeacherListVo> teacherList = teacherMapper.getTeacherDTOList();
        EasyExcel.write(response.getOutputStream())
                .head(TeacherListVo.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("教师信息列表")
                .doWrite(teacherList);

    }
}
